/*
 * MimeToolView.java
 */
package se.jtech.jdf.mimetool;

import java.io.IOException;
import java.util.Enumeration;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.text.StrSubstitutor;
import org.cip4.jdflib.core.JDFDoc;
import org.cip4.jdflib.core.JDFParser;
import org.cip4.jdflib.util.JDFDate;
import org.cip4.jdflib.util.MimeUtil;
import se.jtech.jdf.mimetool.MimeToolApp.Encoding;
import se.jtech.jdf.mimetool.beans.BodyPartBean;
import se.jtech.jdf.mimetool.beans.MultipartBean;

/**
 * The application's main frame.
 */
public class MimeToolView extends FrameView {

    private final String originalTitle;
    private MultipartBean multipartBean = null;
    private File jdfFile = null;
    private ButtonGroup encodingButtonGroup = null;
    private Encoding encoding;

    public MimeToolView(SingleFrameApplication app, Encoding encoding) {
        super(app);
        originalTitle = getFrame().getTitle();
        encodingButtonGroup = new ButtonGroup();
        this.encoding = encoding;
        initComponents();

        // Select button
        Enumeration btns = encodingButtonGroup.getElements();
        while (btns.hasMoreElements()) {
            AbstractButton button = (AbstractButton) btns.nextElement();            
            if (encoding.getName().equals(button.getText())) {
                encodingButtonGroup.setSelected(button.getModel(), true);
            }
        }

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = MimeToolApp.getApplication().getMainFrame();
            aboutBox = new MimeToolAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        MimeToolApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        openArchiceMenuIten = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItem1 = new javax.swing.JMenuItem();
        extractArchiveMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        optionsMenu = new javax.swing.JMenu();
        encodingMenu = new javax.swing.JMenu();
        base64MenuItem = new javax.swing.JRadioButtonMenuItem();
        binaryMenuItem = new javax.swing.JRadioButtonMenuItem();
        bit7MenuItem = new javax.swing.JRadioButtonMenuItem();
        bit8MenuItem = new javax.swing.JRadioButtonMenuItem();
        quotedPrintableMenuItem = new javax.swing.JRadioButtonMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        openArchiveChooser = new javax.swing.JFileChooser();
        extractArchiveChooser = new javax.swing.JFileChooser();
        addJdfFileChooser = new javax.swing.JFileChooser();
        saveArchiveChooser = new javax.swing.JFileChooser();
        jFileChooser1 = new javax.swing.JFileChooser();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Content ID", "File Name", "File Size", "Content Type"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Long.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${multipart.bodyParts}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${CID}"));
        columnBinding.setColumnName("CID");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fileName}"));
        columnBinding.setColumnName("File Name");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${size}"));
        columnBinding.setColumnName("Size");
        columnBinding.setColumnClass(Long.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${contentType}"));
        columnBinding.setColumnName("Content Type");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(se.jtech.jdf.mimetool.MimeToolApp.class).getContext().getResourceMap(MimeToolView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(se.jtech.jdf.mimetool.MimeToolApp.class).getContext().getActionMap(MimeToolView.class, this);
        jMenuItem2.setAction(actionMap.get("addFileToArchive")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        fileMenu.add(jMenuItem2);

        openArchiceMenuIten.setAction(actionMap.get("openArchive")); // NOI18N
        openArchiceMenuIten.setText(resourceMap.getString("openArchiceMenuIten.text")); // NOI18N
        openArchiceMenuIten.setName("openArchiceMenuIten"); // NOI18N
        fileMenu.add(openArchiceMenuIten);

        jSeparator3.setName("jSeparator3"); // NOI18N
        fileMenu.add(jSeparator3);

        jMenuItem3.setAction(actionMap.get("addSubmitQueueEntry")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        fileMenu.add(jMenuItem3);

        jMenuItem4.setAction(actionMap.get("addResubmitQueueEntry")); // NOI18N
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        fileMenu.add(jMenuItem4);

        jMenuItem5.setAction(actionMap.get("addReturnQueueEntry")); // NOI18N
        jMenuItem5.setName("jMenuItem5"); // NOI18N
        fileMenu.add(jMenuItem5);

        jSeparator1.setName("jSeparator1"); // NOI18N
        fileMenu.add(jSeparator1);

        jMenuItem1.setAction(actionMap.get("saveArchive")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        extractArchiveMenuItem.setAction(actionMap.get("extractArchive")); // NOI18N
        extractArchiveMenuItem.setText(resourceMap.getString("extractArchiveMenuItem.text")); // NOI18N
        extractArchiveMenuItem.setName("extractArchiveMenuItem"); // NOI18N
        fileMenu.add(extractArchiveMenuItem);

        jSeparator2.setName("jSeparator2"); // NOI18N
        fileMenu.add(jSeparator2);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        optionsMenu.setText(resourceMap.getString("optionsMenu.text")); // NOI18N
        optionsMenu.setName("optionsMenu"); // NOI18N

        encodingMenu.setText(resourceMap.getString("encodingMenu.text")); // NOI18N
        encodingMenu.setName("encodingMenu"); // NOI18N

        base64MenuItem.setAction(actionMap.get("setEncodingBase64")); // NOI18N
        getEncodingButtonGroup().add(base64MenuItem);
        base64MenuItem.setName("base64MenuItem"); // NOI18N
        encodingMenu.add(base64MenuItem);

        binaryMenuItem.setAction(actionMap.get("setEncodingBinary")); // NOI18N
        getEncodingButtonGroup().add(binaryMenuItem);
        binaryMenuItem.setName("binaryMenuItem"); // NOI18N
        encodingMenu.add(binaryMenuItem);

        bit7MenuItem.setAction(actionMap.get("setEncoding7Bit")); // NOI18N
        getEncodingButtonGroup().add(bit7MenuItem);
        bit7MenuItem.setName("bit7MenuItem"); // NOI18N
        encodingMenu.add(bit7MenuItem);

        bit8MenuItem.setAction(actionMap.get("setEncoding8Bit")); // NOI18N
        getEncodingButtonGroup().add(bit8MenuItem);
        bit8MenuItem.setName("bit8MenuItem"); // NOI18N
        encodingMenu.add(bit8MenuItem);

        quotedPrintableMenuItem.setAction(actionMap.get("setEncodingQuotedPrintable")); // NOI18N
        getEncodingButtonGroup().add(quotedPrintableMenuItem);
        quotedPrintableMenuItem.setName("quotedPrintableMenuItem"); // NOI18N
        encodingMenu.add(quotedPrintableMenuItem);

        optionsMenu.add(encodingMenu);

        menuBar.add(optionsMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 279, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );

        openArchiveChooser.setName("openArchiveChooser"); // NOI18N

        extractArchiveChooser.setDialogTitle(resourceMap.getString("extractArchiveChooser.dialogTitle")); // NOI18N
        extractArchiveChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        extractArchiveChooser.setName("extractArchiveChooser"); // NOI18N

        addJdfFileChooser.setDialogTitle(resourceMap.getString("addJdfFileChooser.dialogTitle")); // NOI18N
        addJdfFileChooser.setName("addJdfFileChooser"); // NOI18N

        saveArchiveChooser.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        saveArchiveChooser.setName("saveArchiveChooser"); // NOI18N

        jFileChooser1.setName("jFileChooser1"); // NOI18N

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void openArchive() {
        final int userInput = openArchiveChooser.showOpenDialog(getComponent());
        if (userInput == JFileChooser.ABORT || userInput == JFileChooser.CANCEL_OPTION) {
            return;
        }
        final File mimeFile = openArchiveChooser.getSelectedFile();
        try {
            final Multipart multipart = MimeUtil.getMultiPart(new FileInputStream(mimeFile));
            setMultipart(multipart);
            setTitle(mimeFile);
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(getComponent(), "Could not open MIME archive: " + e, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    private void setTitle(File file) {
        setTitle(file.getName() + " (" + file.getAbsolutePath() + ")");
    }

    private void setTitle(String title) {
        getFrame().setTitle(originalTitle + " - " + title);
    }

    public synchronized void setMultipart(Multipart multipart) {
        final MultipartBean oldMultipartBean = multipartBean;
        final boolean oldIsAddSubmitQueueEntryEnabled = isAddSubmitQueueEntryEnabled();
        final boolean oldIsAddResubmitQueueEntryEnabled = isAddResubmitQueueEntryEnabled();
        final boolean oldIsAddReturnQueueEntryEnabled = isAddReturnQueueEntryEnabled();
        final boolean oldIsExtractArchiveEnabled = isExtractArchiveEnabled();
        final boolean oldIsSaveArchiveEnabled = isSaveArchiveEnabled();
        multipartBean = new MultipartBean();
        multipartBean.setMultipart(multipart);
        firePropertyChange("multipart", oldMultipartBean, getMultipart());
        firePropertyChange("addSubmitQueueEntryEnabled", oldIsAddSubmitQueueEntryEnabled, isAddSubmitQueueEntryEnabled());
        firePropertyChange("addResubmitQueueEntryEnabled", oldIsAddResubmitQueueEntryEnabled, isAddResubmitQueueEntryEnabled());
        firePropertyChange("addReturnQueueEntryEnabled", oldIsAddReturnQueueEntryEnabled, isAddReturnQueueEntryEnabled());
        firePropertyChange("extractArchiveEnabled", oldIsExtractArchiveEnabled, isExtractArchiveEnabled());
        firePropertyChange("saveArchiveEnabled", oldIsSaveArchiveEnabled, isSaveArchiveEnabled());
    }

    public MultipartBean getMultipart() {
        return multipartBean;
    }

    @Action(enabledProperty = "extractArchiveEnabled", selectedProperty = "extractArchiveEnabled")
    public void extractArchive() {
        final int userInput = extractArchiveChooser.showOpenDialog(getComponent());
        if (userInput == JFileChooser.ABORT || userInput == JFileChooser.CANCEL_OPTION) {
            return;
        }
        final File extractDir = extractArchiveChooser.getSelectedFile();
        if (multipartBean == null) {
            return;
        }
        for (BodyPartBean bodyPartBean : multipartBean.getBodyParts()) {
            BodyPart bodyPart = bodyPartBean.getBodyPart();
            try {
                final String contentType = bodyPartBean.getContentType();
                String fileName = bodyPartBean.getFileName();
                if (fileName == null || fileName.length() == 0) {
                    if (contentType.contains(MimeUtil.VND_JDF)) {
                        fileName = "ticket.jdf";
                    } else if (contentType.contains(MimeUtil.VND_JMF)) {
                        fileName = "message.jmf";
                    } else {
                        fileName = "untitled-" + bodyPartBean.getCID().replaceAll("[^a-zA-Z 0-9]", "-") + "-" + contentType.replaceAll("[^a-zA-Z 0-9]", "-");
                    }
                }
                bodyPart.setFileName(fileName);
                MimeUtil.writeBodyPartToFile(bodyPart, extractDir);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(getComponent(),
                        String.format("Could not extract file '%s' in MIME archive: %s", bodyPartBean.getFileName(), e.toString()), "Error", JOptionPane.ERROR_MESSAGE);
                Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }

    public boolean isExtractArchiveEnabled() {
        return isSaveArchiveEnabled();
    }

    public boolean isSaveArchiveEnabled() {
        return (multipartBean != null) && !multipartBean.getBodyParts().isEmpty();
    }

    public boolean isAddSubmitQueueEntryEnabled() {
        return (multipartBean != null) && !multipartBean.getBodyParts().isEmpty();
    }

    public boolean isAddResubmitQueueEntryEnabled() {
        return (multipartBean != null) && !multipartBean.getBodyParts().isEmpty();
    }

    public boolean isAddReturnQueueEntryEnabled() {
        return (multipartBean != null) && !multipartBean.getBodyParts().isEmpty();
    }

    @Action
    public synchronized void addFileToArchive() {
        final int userInput = addJdfFileChooser.showOpenDialog(getComponent());
        if (userInput == JFileChooser.ABORT || userInput == JFileChooser.CANCEL_OPTION) {
            return;
        }
        jdfFile = addJdfFileChooser.getSelectedFile();
        try {
            final Multipart multipart = MimeUtil.buildMimePackage(null, getJdfDoc(jdfFile), true);
            setMultipart(multipart);
        } catch (Exception e) {
            final String msg = String.format("Could not add JDF file '%s' and its referenced files to the MIME archive: %s", jdfFile.getAbsolutePath(), e.toString());
            JOptionPane.showMessageDialog(getComponent(), msg, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, msg, e);
        }
    }

    @Action(enabledProperty = "saveArchiveEnabled", selectedProperty = "saveArchiveEnabled")
    public synchronized void saveArchive() {
        final int userInput = saveArchiveChooser.showSaveDialog(getComponent());
        if (userInput == JFileChooser.ABORT || userInput == JFileChooser.CANCEL_OPTION) {
            return;
        }
        final File mimeFile = saveArchiveChooser.getSelectedFile();
        try {
            final MimeUtil.MIMEDetails mimeDetails = new MimeUtil.MIMEDetails();
            mimeDetails.transferEncoding = getMultipart().getEncoding();
            MimeUtil.writeToFile(getMultipart().getMultipart(), mimeFile.getAbsolutePath(), mimeDetails);
            setTitle(mimeFile);
        } catch (Exception e) {
            final String msg = String.format("Could not write MIME archive to file '%s': %s", mimeFile.getAbsolutePath(), e.toString());
            JOptionPane.showMessageDialog(getComponent(), msg, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, msg, e);
        }
    }

    private static JDFDoc getJdfDoc(File jdfFile) {
        return new JDFParser().parseFile(jdfFile);
    }

    private static JDFDoc getJdfDoc(String jdfData, String originalFileName) {
        JDFDoc jdfDoc = new JDFParser().parseString(jdfData);
        jdfDoc.setOriginalFileName(originalFileName);
        return jdfDoc;
    }

    private String processJmfTemplate(String resourcePath) throws IOException {
        return processJmfTemplate(resourcePath, new HashMap<String, String>());
    }

    private String processJmfTemplate(String resourcePath, Map<String, String> valuesMap) throws IOException {
        valuesMap.put("senderId", "MimeTool");
        valuesMap.put("timeStamp", new JDFDate().getDateTimeISO());
        valuesMap.put("url", "cid:");
        valuesMap.put("returnJmf", "");
        String jmf = IOUtils.toString(getResourceMap().getClassLoader().getResourceAsStream(resourcePath));
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        return sub.replace(jmf);
    }

    @Action(enabledProperty = "addSubmitQueueEntryEnabled", selectedProperty = "addSubmitQueueEntryEnabled")
    public void addSubmitQueueEntry() {
        String jmf;
        try {
            jmf = processJmfTemplate(getResourceMap().getResourcesDir() + "jmf" + "/CommandSubmitQueueEntry.xml");
        } catch (IOException e) {
            final String msg = String.format("Could not add JMF SubmitQueueEntry to MIME archive because the JMF template could not be processed: %s", e.toString());
            JOptionPane.showMessageDialog(getComponent(), msg, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, msg, e);
            return;
        }
        final Multipart multipart = MimeUtil.buildMimePackage(getJdfDoc(jmf, "SubmitQueueEntry.jmf"), getJdfDoc(jdfFile), true);
        setMultipart(multipart);
    }

    @Action(enabledProperty = "addResubmitQueueEntryEnabled", selectedProperty = "addResubmitQueueEntryEnabled")
    public void addResubmitQueueEntry() {
        String queueEntryID = JOptionPane.showInputDialog("Enter the QueueEntryID of the job to resubmit:");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("queueEntryId", queueEntryID);
        String jmf;
        try {
            jmf = processJmfTemplate(getResourceMap().getResourcesDir() + "jmf" + "/CommandResubmitQueueEntry.xml", valuesMap);
        } catch (IOException e) {
            final String msg = String.format("Could not add JMF ResubmitQueueEntry to MIME archive because the JMF template could not be processed: %s", e.toString());
            JOptionPane.showMessageDialog(getComponent(), msg, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, msg, e);
            return;
        }
        final Multipart multipart = MimeUtil.buildMimePackage(getJdfDoc(jmf, "ResubmitSubmitQueueEntry.jmf"), getJdfDoc(jdfFile), true);
        setMultipart(multipart);
    }

    @Action(enabledProperty = "addReturnQueueEntryEnabled", selectedProperty = "addReturnQueueEntryEnabled")
    public void addReturnQueueEntry() {
        String queueEntryID = JOptionPane.showInputDialog("Enter the QueueEntryID of the job to return:");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("queueEntryId", queueEntryID);
        String jmf;
        try {
            jmf = processJmfTemplate(getResourceMap().getResourcesDir() + "jmf" + "/CommandReturnQueueEntry.xml", valuesMap);
        } catch (IOException e) {
            final String msg = String.format("Could not add JMF ReturnQueueEntry to MIME archive because the JMF template could not be processed: %s", e.toString());
            JOptionPane.showMessageDialog(getComponent(), msg, "Error", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(MimeToolView.class.getName()).log(Level.SEVERE, msg, e);
            return;
        }
        final Multipart multipart = MimeUtil.buildMimePackage(getJdfDoc(jmf, "ReturnSubmitQueueEntry.jmf"), getJdfDoc(jdfFile), true);
        setMultipart(multipart);
    }

    public ButtonGroup getEncodingButtonGroup() {
        return encodingButtonGroup;
    }

    @Action
    public void setEncoding7Bit() {
        if (getMultipart() != null) {
            getMultipart().setEncoding(Encoding.Bit7.getName());
        }
        setEncoding(Encoding.Bit7);
    }

    @Action
    public void setEncoding8Bit() {
        if (getMultipart() != null) {
            getMultipart().setEncoding(Encoding.Bit8.getName());
        }
        setEncoding(Encoding.Bit8);
    }

    @Action
    public void setEncodingQuotedPrintable() {
        if (getMultipart() != null) {
            getMultipart().setEncoding(Encoding.QuotedPrintable.getName());
        }
        setEncoding(Encoding.QuotedPrintable);
    }

    @Action
    public void setEncodingBase64() {
        if (getMultipart() != null) {
            getMultipart().setEncoding(Encoding.Base64.getName());
        }
        setEncoding(Encoding.Base64);
    }

    @Action
    public void setEncodingBinary() {
        if (getMultipart() != null) {
            getMultipart().setEncoding(Encoding.Binary.getName());
        }
        setEncoding(Encoding.Binary);
    }

    public void setEncoding(Encoding encoding) {
        this.encoding = encoding;
    }

    public Encoding getEncoding() {
        return encoding;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser addJdfFileChooser;
    private javax.swing.JRadioButtonMenuItem base64MenuItem;
    private javax.swing.JRadioButtonMenuItem binaryMenuItem;
    private javax.swing.JRadioButtonMenuItem bit7MenuItem;
    private javax.swing.JRadioButtonMenuItem bit8MenuItem;
    private javax.swing.JMenu encodingMenu;
    private javax.swing.JFileChooser extractArchiveChooser;
    private javax.swing.JMenuItem extractArchiveMenuItem;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JTable jTable1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openArchiceMenuIten;
    private javax.swing.JFileChooser openArchiveChooser;
    private javax.swing.JMenu optionsMenu;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JRadioButtonMenuItem quotedPrintableMenuItem;
    private javax.swing.JFileChooser saveArchiveChooser;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
